/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.kz.shange.imgSvc;

import com.baidu.inf.iis.bcs.BaiduBCS;
import com.baidu.inf.iis.bcs.auth.BCSCredentials;
import com.baidu.inf.iis.bcs.http.HttpMethodName;
import com.baidu.inf.iis.bcs.model.ObjectMetadata;
import com.baidu.inf.iis.bcs.request.GenerateUrlRequest;
import com.baidu.inf.iis.bcs.request.PutObjectRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 *
 * @author Administrator
 */
public class BCSSvc {

    private String host;
    private String accessKey;
    private String secretKey;
    private String mediaBucket;

    public BCSSvc() {
        host = "bcs.duapp.com";
        accessKey = "qygPOSNajKNlg1zrPEehXtr3";
        secretKey = "y6DadokxPZkBoqoFVhxRG135tbbYhD21";
        mediaBucket = "kz-shange-imgs1";
    }

    public BaiduBCS getBaiduBCS() {
        BCSCredentials credentials = new BCSCredentials(accessKey, secretKey);
        BaiduBCS baiduBCS = new BaiduBCS(credentials, host);
        baiduBCS.setDefaultEncoding("UTF-8"); // Default UTF-8
        return baiduBCS;
    }

    public void generateMediaUrl(String mediaName) {
        BaiduBCS baiduBCS = this.getBaiduBCS();
        GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(HttpMethodName.GET, mediaBucket, mediaName);
        System.out.println(baiduBCS.generateUrl(generateUrlRequest));
    }

    public void uploadMediaByUrl(String mediaUrl) throws MalformedURLException, IOException {
        URL url = new URL(mediaUrl);
        URLConnection conn = url.openConnection();
        long l = conn.getContentLengthLong();
        String t = conn.getContentType();
        String fileName = "/"+UUID.randomUUID().toString().replaceAll("-", "")+".jpg";
        InputStream is=conn.getInputStream();
        this.uploadFileToBD(is, fileName, l, t);
    }

    public void uploadMedia(String filePath, String fileName) throws FileNotFoundException {
        BaiduBCS baiduBCS = this.getBaiduBCS();
        File file = new File(filePath);

        InputStream fileContent = new FileInputStream(file);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpeg");
        objectMetadata.setContentLength(file.length());
        PutObjectRequest request = new PutObjectRequest(this.mediaBucket, fileName, fileContent, objectMetadata);
        ObjectMetadata result = baiduBCS.putObject(request).getResult();
        log(result.toString());
    }

    public void getMedia(String url, String filePathName) {
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
            HttpResponse response = httpclient.execute(httpget);

            File storeFile = new File(filePathName);
            FileOutputStream output = new FileOutputStream(storeFile);

// 得到网络资源的字节数组,并写入文件
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    byte b[] = new byte[1024];
                    int j = 0;
                    while ((j = instream.read(b)) != -1) {
                        output.write(b, 0, j);
                    }
                    output.flush();
                    output.close();
                } catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
                    throw ex;
                } catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection immediately.
                    httpget.abort();
                    throw ex;
                } finally {
// Closing the input stream will trigger connection release
                    try {
                        instream.close();
                    } catch (Exception ignore) {
                    }
                }
            }

        } catch (Exception e) {
            log(e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

//<editor-fold defaultstate="collapsed" desc="property">
    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getMediaBucket() {
        return mediaBucket;
    }

    public void setMediaBucket(String mediaBucket) {
        this.mediaBucket = mediaBucket;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }
//</editor-fold>

    private void log(String msg) {
        System.out.println(msg);
    }

    private void uploadFileToBD(InputStream is, String fileName, long fileLength, String fileType) {
        BaiduBCS baiduBCS = this.getBaiduBCS();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(fileType);
        objectMetadata.setContentLength(fileLength);
        PutObjectRequest request = new PutObjectRequest(this.mediaBucket, fileName, is, objectMetadata);
        ObjectMetadata result = baiduBCS.putObject(request).getResult();
        log(result.toString());
    }
}
